/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package transervfx.Dato.DAO;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import transervfx.Dato.Entidad.Juridico;

/**
 *
 * @author silvi
 */
public class ClienteJuridicoDAO implements Dao<Juridico, Long> {

    private static ClienteJuridicoDAO INSTANCE = null;

    /**
     * Crea el Gestor Auxiliar
     */
    protected ClienteJuridicoDAO() {
    }

    /**
     * creador sincronizado para protegerse de posibles problemas multi-hilo
     * otra prueba para evitar instanciaciÃ³n mÃºltiple
     */
    private synchronized static void createInstance() {
        if (INSTANCE == null) {
            INSTANCE = new ClienteJuridicoDAO();
        }
    }

    /**
     * Obtiene la instancia.
     *
     * @return devuelve la instancia del "GestorAuxiliar".
     */
    public static ClienteJuridicoDAO getInstance() {
        if (INSTANCE == null) {
            createInstance();
        }
        return INSTANCE;
    }

    @Override
    public void persist(Juridico entity) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {
            EntityTransaction t = em.getTransaction();
            try {
                t.begin();
                em.persist(entity);
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
    }

    @Override
    public void remove(Juridico entity) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {

            EntityTransaction t = em.getTransaction();
            try {
                t.begin();
                System.out.println("ESTAS POR ELIMIAR");
                entity = em.getReference(Juridico.class, entity.getId());
                em.remove(entity);
                System.out.println("LO ELIMINA");
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
    }

    @Override
    public void update(Juridico entity) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {


            em.getTransaction().begin();
            System.out.println("Entra a modificar el Juridico");
            em.merge(entity);

            em.getTransaction().commit();
            System.out.println("Lo modifica al Juridico");

        } finally {
            em.close();
        }
    }

    @Override
    public Juridico findById(Long id) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {

            return em.getReference(Juridico.class, id);

        } finally {
            em.close();
        }
    }

    @Override
    public List<Juridico> findAll() {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {

            return em.createNamedQuery("Juridico.findAll").getResultList();

        } finally {
            em.close();
        }
    }

    public Juridico findByCompleto(Juridico clienteJuridicoSeleccionado) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {

            //poner find no reference
            clienteJuridicoSeleccionado = em.find(Juridico.class, clienteJuridicoSeleccionado.getId());

            clienteJuridicoSeleccionado.getDomicilio();

            if (!clienteJuridicoSeleccionado.getLugaresPersonalesFrecuentes().isEmpty()) {
                clienteJuridicoSeleccionado.getLugaresPersonalesFrecuentes().get(0);
            }
            return clienteJuridicoSeleccionado;

        } finally {
            em.close();
        }
    }

    public Juridico findByRazonSocial(String razonSocial) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {



            Query query = em.createNamedQuery("Juridico.findByRazonSocial");
            query.setParameter("razonSocial", razonSocial);

            if (query.getResultList().isEmpty()) {
                return null;
            }
            return (Juridico) query.getResultList().get(0);


        } finally {
            em.close();
        }
    }

    public Juridico findByCuit(Integer cuit) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {
            Query query = em.createNamedQuery("Juridico.findByCuit");
            query.setParameter("cuit", cuit);
            if (query.getResultList().isEmpty()) {
                return null;
            } else {
                return (Juridico) query.getResultList().get(0);
            }
        } finally {
            em.close();
        }
    }

    public Juridico findByRazonSocialAndCuit(String razonSocial, Integer cuit) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {


            Query query = em.createNamedQuery("Juridico.findByRazonSocialAndCuit");
            query.setParameter("razonSocial", razonSocial);
            query.setParameter("cuit", cuit);

            List<Juridico> lr = query.getResultList();
            if (lr.size() > 0) {
                return lr.get(0);
            } else {
                return null;
            }

        } finally {
            em.close();
        }
    }

    // FALTA HACER SI ME PODES AYUDAR OSCAR!!! 
    //SILVI CREO QUE ES ASI. Meli
    public boolean poseeDeuda(Juridico r) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {


            Juridico rAux = em.find(Juridico.class, r.getId());
            System.out.println("TRAE AL CLIENTE");
            if (rAux.getDeuda() != null) {
                System.out.println("LA deuda NO ES NULL => POSEE DEUDA");
                return true;
            }
            System.out.println("NO POSEE deuda");
            return false;

        } finally {
            em.close();
        }

    }

    public Long numeroDeClientesJuridicosFiltrados(String razonSocial, Integer cuit, String condicionIva) {
        System.out.println("Entra numeroDeClientesJuridicosFiltrados");
        System.out.println("condicionIva: " + condicionIva);


        String consulta = "SELECT COUNT(p) FROM Juridico p ";

        boolean hayotroParametro = false;

        if (!razonSocial.equals("") || cuit != null || !condicionIva.equals("")) {

            consulta = "SELECT COUNT(p) FROM Juridico p WHERE";

            if (!razonSocial.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }

                consulta = consulta + " p.razonSocial LIKE " + "'" + razonSocial + "%'";
                hayotroParametro = true;
            }

            if (cuit != null) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }
                consulta = consulta + " p.cuit =" + cuit;
            }

            if (!condicionIva.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }
                consulta = consulta + " p.condicionFrenteIva LIKE " + "'" + condicionIva + "'";
            }

        }


        System.out.println(consulta);
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {
            Query query = em.createQuery(consulta);

            return (Long) query.getSingleResult();

        } finally {
            em.close();
        }
    }

    public List<Juridico> buscarPorFiltroRango(String razonSocial, Integer cuit, String condicionIva, int ini, int fin) {
        System.out.println("Entra buscarPorFiltroRangoJuridico");
        System.out.println("razonSocial: " + razonSocial);
        System.out.println("condicionIva: " + condicionIva);

        String consulta = "SELECT p FROM Juridico p";
        boolean hayotroParametro = false;

        if (!razonSocial.equals("") || cuit != null || !condicionIva.equals("")) {

            consulta = "SELECT p FROM Juridico p WHERE";

            if (!razonSocial.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }

                consulta = consulta + " p.razonSocial LIKE " + "'" + razonSocial + "%'";
                hayotroParametro = true;
            }

            if (cuit != null) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }
                consulta = consulta + " p.cuit =" + cuit;
            }

            if (!condicionIva.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }
                consulta = consulta + " p.condicionFrenteIva LIKE " + "'" + condicionIva + "'";
            }

        }
        System.out.println(consulta);

        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {
            Query query = em.createQuery(consulta);
            query.setFirstResult(ini);
            query.setMaxResults(fin);

            return (List<Juridico>) query.getResultList();

        } finally {
            em.close();
        }
    }

    public Juridico findJuridicoByCuit(Integer cuit) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {
            Query query = em.createNamedQuery("Juridico.findByCuit");
            query.setParameter("cuit", cuit);
            if (query.getResultList().isEmpty()) {
                return null;
            }
            return (Juridico) query.getResultList().get(0);
        } finally {
            em.close();
        }
    }
}
